import React, { useEffect, useState } from 'react';
import { List, Avatar, Badge, Tooltip } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import './OnlineUsers.css';

/**
 * 显示在线协作用户组件
 * @param {Object} props
 * @param {Array} props.users - 在线用户列表
 * @param {Object} props.selectedObjects - 用户选中的对象映射
 */
const OnlineUsers = ({ users = [], selectedObjects = {} }) => {
  const [displayUsers, setDisplayUsers] = useState([]);

  useEffect(() => {
    // 处理用户数据，添加选中对象信息
    const processedUsers = users.map(user => {
      return {
        ...user,
        selectedObjectId: selectedObjects[user.clientId] || null
      };
    });
    setDisplayUsers(processedUsers);
  }, [users, selectedObjects]);

  if (!displayUsers.length) {
    return null;
  }

  return (
    <div className="online-users-container">
      <div className="online-users-header">在线用户 ({displayUsers.length})</div>
      <List
        size="small"
        dataSource={displayUsers}
        virtual
        height={300}
        itemHeight={47}
        renderItem={user => (
          <List.Item>
            <List.Item.Meta
              avatar={
                <Badge dot={!!user.selectedObjectId} color={user.color || '#1890ff'}>
                  <Avatar
                    style={{ backgroundColor: user.color || '#1890ff' }}
                    icon={<UserOutlined />}
                  />
                </Badge>
              }
              title={
                <Tooltip 
                  title={user.selectedObjectId ? '正在编辑对象' : '正在查看'} 
                  placement="right"
                >
                  <span style={{ color: user.color || '#1890ff' }}>
                    {user.name || `用户${user.clientId.substring(0, 4)}`}
                  </span>
                </Tooltip>
              }
            />
          </List.Item>
        )}
      />
    </div>
  );
};

const areEqual = (prevProps, nextProps) => {
  // 快速比较引用
  if (prevProps === nextProps) return true;
  
  // 比较users数组
  if (prevProps.users.length !== nextProps.users.length) {
    return false;
  }
  
  // 比较每个用户的关键属性
  const usersEqual = prevProps.users.every((user, i) => {
    const nextUser = nextProps.users[i];
    return (
      user.clientId === nextUser.clientId &&
      user.name === nextUser.name &&
      user.color === nextUser.color
    );
  });
  
  // 比较selectedObjects
  const prevSelected = prevProps.selectedObjects;
  const nextSelected = nextProps.selectedObjects;
  const selectedKeys = Object.keys(prevSelected);
  
  if (selectedKeys.length !== Object.keys(nextSelected).length) {
    return false;
  }
  
  // 比较每个selectedObject的值
  const selectedObjectsEqual = selectedKeys.every(key => 
    prevSelected[key] === nextSelected[key]
  );
    
  return usersEqual && selectedObjectsEqual;
};

export default React.memo(OnlineUsers, areEqual);